import path from "path"
import fs from "fs"

const titleMark: string = '---'
const titleAttrs: Array<string> = ['title', 'date', 'tags']

/**
 * 读取博客内容
 * @param mdPath 博客文件路径
 * @returns 返回博客数据
 */
function readMDFile(mdPath: string) {
    let data: string = fs.readFileSync(path.resolve(mdPath), { encoding: 'utf-8' });
    let cloumnData: Array<string> = data.split('\n')
    // 打印文件前10行内容和总行数
    let outputLen = cloumnData.length > 10 ? 10 : cloumnData.length
    for (let i = 0; i < outputLen; i++) {
        console.log(`[${i}] :>> `, cloumnData[i]);
    }
    if (cloumnData.length > outputLen) {
        console.log('... :>> ... ');
    }
    console.log('fileDataLength :>> ', cloumnData.length);
    // 找到标题信息模块
    let lineArr: Array<number> = []
    let titleObj: titleObj = {
        title: '',
        date: '',
        tags: ''
    }
    cloumnData.forEach((item: string, index: number) => {
        if (item.trim() == titleMark) {
            lineArr.push(index)
        }
        // 找到一级标题 
        // if (item.trim().startsWith("# ")) {

        // }
    })
    console.log('lineArr :>> ', lineArr);
    if (lineArr.length >= 2) {
        for (let i: number = lineArr[0] + 1; i < lineArr[1]; i++) {
            let line = cloumnData[i]
            console.log('line :>> ', line);
            getTitleInfo(line, titleObj)
        }
    }
    console.log('titleObj :>> ', titleObj);

    let result: blogContent = {
        mdContent: cloumnData.splice(lineArr[1] + 1),
        titleObj: titleObj
    }
    return result
}

/**
 * 为标题对应属性对象赋值
 * @param str 要处理的属性字符串
 * @param titleObj 传入的标题对象
 */
function getTitleInfo(str: string, titleObj: object) {
    titleAttrs.forEach((attr: string) => {
        let index = str.indexOf(attr)
        if (index >= 0) {
            Object.defineProperty(titleObj, attr, {
                value: str.substring(index + attr.length + 2).trim(),
                enumerable: true
            })
        }
    })
}
/**
 * 时间格式化函数
 * @param time 时间（数字）
 * @param cFormat 时间格式
 * @returns 格式化后的时间字符串
 */
function parseTime(time: number, cFormat?: string) {
    if (!time) {
        return "--";
    }
    const formate = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
    let date;
    if (typeof time === "object") {
        date = time;
    } else {
        if (typeof time === "string" && /^[0-9]+$/.test(time)) {
            time = parseInt(time);
        }
        if (typeof time === "number" && time.toString().length === 10) {
            time = time * 1000;
        }
        date = new Date(time);
    }
    const formatObj: formatDate = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    };
    const time_str = formate.replace(/{(y|m|d|h|i|s|a)+}/g, (result: string, key: string) => {
        let value: string | number = formatObj[key];
        // Note: getDay() returns 0 on Sunday
        if (key === "a") {
            return ["日", "一", "二", "三", "四", "五", "六"][value];
        }
        if (result.length > 0 && value < 10) {
            value = "0" + value;
        }
        return value.toString() || '0';
    });
    return time_str;
}

// let mdPath = 'C:\\Users\\cuipp0509\\Documents\\WPS Cloud Files\\279367518\\博客'
// // let mdPath = 'C:\\Users\\duan\\Documents\\WPS Cloud Files\\279367518\\博客';
// let blogName = 'http-udp-ip-split.md'
// readMDFile(mdPath + '\\' + blogName)

export {
    readMDFile,
    parseTime
}